package com.sgb.kjwl.view.ui.activity.manage

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityWebsiteInquiryBinding
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent
import com.sgb.kjwl.di.manage.EnterpriseManageModule
import com.sgb.kjwl.view.ui.fragment.manage.OtherInquiryFragment
import com.sgb.kjwl.view.ui.fragment.manage.WebSiteInquiryFragment
import com.sgb.kjwl.view.ui.fragment.self.MyInquiryLeaseFragment
import com.sgb.kjwl.viewmodel.manage.WebSiteInquiryModel
import com.swgk.core.base.di.AppComponent
import javax.inject.Inject

/**
 * 函询列表（企业、个人、团队）
 */
class WebSiteInquiryActivity : AppActivity() {

    @Inject
    lateinit var mModel: WebSiteInquiryModel

    private lateinit var mBinding: ActivityWebsiteInquiryBinding

    private lateinit var mAdapter: InquiryPageAdapter

    private var mSecondTitles = arrayListOf("招采", "集采", "商品", "租赁", "工队", "网站", "服务")

    private var mShopNum = "" //函询商品数量

    companion object {
        private  val mTitles = arrayOf("收到的函询", "发起的函询")

        const val TYPE_CLICK_TYPE = 1233
        const val TYPE_CLICK_STATUS = 1234
        const val TYPE_REPLYED = 1
        const val TYPE_UNREPLY = 0
        private const val TYPE_SHOP_NUM = "key_shop_num"
        fun start(context: Context?) {
            start(context, "")
        }

        fun start(context: Context?, shopNum : String) {
            val intent = Intent(context, WebSiteInquiryActivity::class.java)
            intent.putExtra(TYPE_SHOP_NUM, shopNum)
            context!!.startActivity(intent)
        }
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
            .enterpriseManageModule(EnterpriseManageModule(this)).build().inject(this)
    }

    override fun initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_website_inquiry)
        if (intent != null){
            mShopNum = intent.getStringExtra(TYPE_SHOP_NUM)
        }
        if (TextUtils.isEmpty(mShopNum)){
            mShopNum = "0"
        }
        mBinding.include.titleView.text = "函询列表"
        mBinding.include.ivBack.setOnClickListener(this)
        renderFirstTab()
        renderSecondTab()
        renderData(0)
    }

    private fun renderData(position : Int){
        val tabCount = mBinding.secondTablayout.tabCount
        for (i in 0 until tabCount){
            if (mBinding.secondTablayout.getTabAt(i)!!.text.toString().contains("网站")){
                if (position == 0){
                    mAdapter.setPageTitle(i, "网站($mShopNum)")
                } else {
                    mAdapter.setPageTitle(i, "网站")
                }
                break
            }
        }
    }

    fun setTextNum(num : Int){
        if(mBinding.secondTablayout.getTabAt(mBinding.viewPage.currentItem)!!.text.toString().contains("租赁")){
            mAdapter.setPageTitle(mBinding.viewPage.currentItem, "租赁("+num+")")
        }
    }

    private fun renderFirstTab() {
        for (item in mTitles) {
            val tab: TabLayout.Tab = mBinding.tablayout.newTab()
            tab.text = item
            mBinding.tablayout.addTab(tab)
        }
        mBinding.tablayout.getTabAt(0)!!.select()
        mBinding.tablayout.tabMode = TabLayout.MODE_FIXED
        mBinding.tablayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                refreshInquiryFragment(true)
                renderData(tab!!.position)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })
    }

    fun refreshInquiryFragment(isChangeType : Boolean){
//        val fragment = supportFragmentManager.findFragmentByTag(
//            "android:switcher:" + mBinding.viewPage.id.toString() + ":" + 5)
        val fragment = supportFragmentManager.findFragmentByTag(
                "android:switcher:" + mBinding.viewPage.id.toString() + ":" + mBinding.viewPage.currentItem)

        if (fragment != null && fragment is WebSiteInquiryFragment) {
            if (mBinding.viewPage.currentItem == 5) {
                fragment.setTypeInquiry(
                    if (mBinding.tablayout.selectedTabPosition == 0)
                        WebSiteInquiryFragment.TYPE_MY_REPLY else WebSiteInquiryFragment.TYPE_MY_POST)
            } else {
                if (isChangeType) {
                    fragment.setInitTypeInquiry(
                        if (mBinding.tablayout.selectedTabPosition == 0)
                            WebSiteInquiryFragment.TYPE_MY_REPLY else WebSiteInquiryFragment.TYPE_MY_POST
                    )
                }
            }
        }else if(fragment != null && fragment is MyInquiryLeaseFragment){
            if (mBinding.viewPage.currentItem == 3) {
                fragment.setTypeInquiry(mBinding.tablayout.selectedTabPosition)
            }
        }
    }


    private fun renderSecondTab() {
        mAdapter = InquiryPageAdapter(supportFragmentManager, mSecondTitles)
        mBinding.viewPage.adapter = mAdapter
        mBinding.viewPage.offscreenPageLimit = mSecondTitles.size
        mBinding.secondTablayout.setupWithViewPager(mBinding.viewPage)
        mBinding.secondTablayout.tabMode = TabLayout.MODE_SCROLLABLE
        mBinding.viewPage.currentItem = 0
        mBinding.secondTablayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })
        mBinding.viewPage.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                refreshInquiryFragment(false)
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v!!.id){
            R.id.iv_back -> {
                finish()
            }
        }
    }


    class InquiryPageAdapter(fm : FragmentManager, mTitles : ArrayList<String>) : FragmentPagerAdapter(fm) {
        private var mTitles : ArrayList<String> ?= null
        init {
            this.mTitles = mTitles
        }
        override fun getCount(): Int {
            if (mTitles == null){
                return 0
            }
            return mTitles!!.size
        }

        // 动态设置我们标题的方法

        fun setPageTitle(position: Int, title : String){
            if (position >= 0 && position < mTitles!!.size){
                mTitles!![position] = title
                notifyDataSetChanged()
            }
        }

        override fun getItem(position: Int): Fragment {
            if (mTitles == null) return OtherInquiryFragment.newInstance()
            if (mTitles!![position].contains("网站")){
                return WebSiteInquiryFragment.newInstance()
            }else if (mTitles!![position].contains("租赁")){
                return MyInquiryLeaseFragment.newInstance()
            }
            return OtherInquiryFragment.newInstance()
        }

        override fun getPageTitle(position: Int): CharSequence {
            if (mTitles != null){
                return mTitles!![position]
            }
            return ""
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == WebSiteInquiryFragment.REQUEST_CODE_H5) {
            refreshInquiryFragment(false)
        }
    }
}





